import { FastifyInstance } from "fastify";
import { Static, Type } from "@sinclair/typebox";
import { config } from "@config";
import { Student } from "@db";

const studentParams = Type.Object({
    studentId: Type.Number(),
});

export const student = async (fastify: FastifyInstance) => {
    fastify.get<{
        Params: Static<typeof studentParams>;
    }>(
        "/student/:studentId",
        {
            schema: {
                tags: ["student"],
                params: studentParams,
            },
        },
        async (req, res) => {
            const { studentId } = req.params;

            const student = await Student.findOne({
                where: {
                    id: studentId,
                },
            });

            return res.send({
                ...student.dataValues,
                photo: student.photo
                    ? "https://" +
                      config.host +
                      "/files/avatars/" +
                      student.photo
                    : null,
                password: undefined,
                createdAt: undefined,
                updatedAt: undefined,
            });
        }
    );

    fastify.get(
        "/student",
        {
            preHandler: fastify.auth("student"),
            schema: {
                tags: ["student"],
            },
        },
        async (req, res) => {
            return res.send({
                ...req.student.dataValues,
                photo: req.student.photo
                    ? "https://" +
                      config.host +
                      "/files/avatars/" +
                      req.student.photo
                    : null,
                password: undefined,
                createdAt: undefined,
                updatedAt: undefined,
            });
        }
    );
};
